import UserImformation.Account;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

@WebServlet("/ChangeHeadImgServlet")
public class ChangeHeadImgServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Map<String, String> infoMap = (Map<String, String>) req.getSession().getAttribute("user");
        String user_name = infoMap.get("username");

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("myDateBase");
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        int exit = 0;

        String jpql = "select a from Account a where a.username = :username";
        Query query = em.createQuery(jpql);
        query.setParameter("username",user_name);
        Account account = (Account)query.getSingleResult();

        if(account != null) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload;
            upload = new ServletFileUpload(factory);
            List<FileItem> list = null;
            String head_img = null;
            try {
                list = upload.parseRequest(req);
                for (FileItem fi : list) {
                    if (!fi.isFormField()) {
                        if (fi.getSize() != 0) {
                            head_img = fi.getName();
                            String path = getServletContext().getRealPath("/headImages");
                            InputStream is = fi.getInputStream();
                            FileOutputStream os = new FileOutputStream(new File(path, head_img));
                            IOUtils.copy(is, os);
                            os.close();
                            is.close();
                            fi.delete();
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            account.setImg(head_img);

            em.persist(account);
            tx.commit();
            em.close();

            resp.sendRedirect("/user.jsp");
        }
    }
}
